/*
 * @Author: zi.yang
 * @Date: 2024-11-05 15:24:30
 * @LastEditors: zi.yang
 * @LastEditTime: 2024-11-06 16:54:42
 * @Description: 
 * @FilePath: /save-gitee-img/GiteeApi.js
 */
import process from 'node:process';

export default class GiteeApi {
  baseUrl = "https://gitee.com/api/v5";
  token = "";
  owner = "";
  repo = "";

  constructor(token, owner, repo) {
    this.token = token || process.env.GITEE_ACCESS_TOKEN;
    this.owner = owner || process.env.GITEE_REPO_OWNER;
    this.repo = repo || process.env.GITEE_REPO_NAME;
  }

  request(url, data, method = "GET") {
    return fetch(`${this.baseUrl}/${url}`, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `token ${this.token}`,
      },
      body: method === 'POST' ? JSON.stringify(data) : undefined,
      params: method === 'GET' ? data : undefined,
      method
    })
      .then((res) => res.json());
  }

  uploadImage(path, base64Data = '', message = "create file") {
    if (!base64Data) {
      return Promise.reject({ message: "No File Base64 Data" });
    }
    const content = base64Data.indexOf(",") > -1 ? base64Data.split(",")[1] : base64Data;
    return this.request(`repos/${this.owner}/${this.repo}/contents/${path}`, { message, content, }, 'POST');
  }
}
